import { logoutApi } from "@/api/modules/login";

import { editUser, getUser, modifyUserPassWord } from "@/api/modules/user";
import AutoSaveInput from "@/components/Frame/auto-save-input";
import UploadImg from "@/components/Upload/Img.vue";
import { DEMOID, LOGIN_URL } from "@/config/config";
import { changeUserData, changeUserInfo } from "@/hooks/useUserData";
import "@/layouts/components/ThemeDrawer/index.scss";
import { GlobalStore } from "@/stores";
import { AuthStore } from "@/stores/modules/auth";
import { showTips } from "@/utils/util";
import { ElForm, ElMessageBox } from "element-plus";
import { getCurrentInstance, defineComponent, reactive, ref, ComponentInternalInstance } from "vue";
import { useRouter } from "vue-router";
import UserDetailDialog from "./../components/form.vue";
import "./user-profile.scss";

export default defineComponent({
	setup() {
		return () => {
			return (
				<div class="user-profile">
					<BasicInfo class="bg-white p-8" />
					<div class="flex">
						<div class="flex-row w-1/3 mr-4">
							<PwdInfo class="bg-white p-8 mt-4" />
						</div>
						<div class="flex-1">
							<LayoutInfo class="bg-white p-8 mt-4" />
						</div>
					</div>
				</div>
			);
		};
	}
});

import defaultImg from "@/assets/images/user.png";
import { ResultEnum } from "@/enums/httpEnum";
import { filePrefix } from "@/hooks/useSystem";
import { PublicStore } from "@/stores/modules/public";
const BasicInfo = defineComponent({
	setup() {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const demoId = ref(DEMOID);
		const publicStore = PublicStore();
		const userInfo = ref<any>({});
		initUser();

		const EmailInputRef = ref<any>();
		const MobileInputRef = ref<any>();
		const saveUserField = async (target: "email" | "mobile") => {
			let value;
			if (target == "email") {
				value = userInfo.value.email;
				EmailInputRef.value.unFocus();
			} else if (target == "mobile") {
				value = userInfo.value.mobile;
				MobileInputRef.value.unFocus();
			} else {
				return;
			}
			await changeUserInfo(target, value);
		};
		async function initUser() {
			let { result } = await getUser(publicStore.userInfo.username);
			userInfo.value = result || {};
		}
		// 打开 drawer(新增、查看、编辑)
		const drawerRef = ref();
		const openDrawer = () => {
			let params = {
				title: proxy?.$t("porfile.dialog_title.edit"),
				rowData: { ...userInfo.value },
				api: editUser
			};
			drawerRef.value.acceptParams(params);
		};
		const avatarEl = ref();
		const uploadAvatar = async (res: any) => {
			//上传成功
			if (res.code == ResultEnum.SUCCESS) {
				userInfo.value.avatar = res.result;
				//更新用户信息
				await updateUser();
			}
		};
		const cleanAvatar = async () => {
			userInfo.value.avatar = "";
			//更新用户信息
			await updateUser();
		};
		const updateUser = async () => {
			let ok = await changeUserData(userInfo.value, ["avatar"]);
			if (ok) {
				initUser();
			}
		};
		return () => {
			return (
				<div class="user-profile">
					<UserDetailDialog class="user-profile-dialog" ref={drawerRef} />
					<div class="group-title font-bold pb-3 mb-2 border-b-2 flex justify-between">
						{proxy?.$t("porfile.card_title.basic_info")}
						<el-link
							type="primary"
							class="iconfont iconedit-3"
							disabled={demoId.value == userInfo.value.id}
							onClick={() => openDrawer()}
						>
							{proxy?.$t("porfile.link.edit")}
						</el-link>
					</div>
					<div class="flex user-basic-info pt-12 pb-8 pl-10 pr-4">
						<div class="pl-10 pr-12" style="width:230px">
							<UploadImg
								ref={avatarEl}
								currentDefault={userInfo.value.avatar ? false : true}
								imageUrl={userInfo.value.avatar ? filePrefix() + userInfo.value.avatar : defaultImg}
								emptyTips="用戶图片"
								height="150px"
								width="150px"
								fileSize={0.1}
								autoUpload
								showTips={false}
								onCleanImage={cleanAvatar}
								onSubmit={uploadAvatar}
							></UploadImg>
							<div class="text-center primary-color" style="width:150px;">
								{userInfo.value.alias || userInfo.value.username}
							</div>
						</div>
						<el-form label-width="100px" size="small" class="flex-1 pr-12" label-position="left">
							<el-form-item
								label="Email："
								v-slots={{
									label: () => {
										return (
											<>
												<span class="pr-2 iconfont iconmail"></span>
												<span>{proxy?.$t("porfile.form_label.email")}</span>
											</>
										);
									}
								}}
							>
								<div class="flex justify-between w-full">
									<AutoSaveInput
										ref={EmailInputRef}
										v-model={userInfo.value.email}
										placeholder={proxy?.$t("porfile.placeholder.email")}
										onChange={() => saveUserField("email")}
										sufixBtn={demoId.value != userInfo.value.id}
									/>
								</div>
							</el-form-item>
							<el-form-item
								label={proxy?.$t("porfile.form_label.mobile")}
								v-slots={{
									label: () => {
										return (
											<>
												<span class="pr-2 iconfont iconsmartphone"></span>
												<span>{proxy?.$t("porfile.form_label.mobile")}</span>
											</>
										);
									}
								}}
							>
								<div class="flex justify-between w-full">
									<AutoSaveInput
										ref={MobileInputRef}
										v-model={userInfo.value.mobile}
										placeholder={proxy?.$t("porfile.placeholder.mobile")}
										onChange={() => saveUserField("mobile")}
										sufixBtn={demoId.value != userInfo.value.id}
									/>
								</div>
							</el-form-item>
							<el-form-item
								label={proxy?.$t("porfile.form_label.role")}
								v-slots={{
									label: () => {
										return (
											<>
												<span class="pr-2 iconfont iconuser-check"></span>
												<span>{proxy?.$t("porfile.form_label.role")}</span>
											</>
										);
									}
								}}
							>
								{userInfo.value.roleName || "--"}
							</el-form-item>
							<el-form-item
								label={proxy?.$t("porfile.form_label.company")}
								v-slots={{
									label: () => {
										return (
											<>
												<span class="pr-2 iconfont iconbx-building-house"></span>
												<span>{proxy?.$t("porfile.form_label.company")}</span>
											</>
										);
									}
								}}
							>
								{userInfo.value.company || "--"}
							</el-form-item>
							{/* <el-form-item
								label="分组："
								v-slots={{
									label: () => {
										return (
											<>
												<span class="pr-2 iconfont iconbx-group"></span>
												<span>分组：</span>
											</>
										);
									}
								}}
							>
								<el-tooltip show-after={500} content={userInfo.value.deptName}>
									<div class="truncate">{userInfo.value.deptName || "--"}</div>
								</el-tooltip>
							</el-form-item> */}
							<el-form-item
								label={proxy?.$t("porfile.form_label.token_exp")}
								v-slots={{
									label: () => {
										return (
											<>
												<span class="pr-2 iconfont iconbx-time"></span>
												<span>{proxy?.$t("porfile.form_label.token_exp")}</span>
											</>
										);
									}
								}}
							>
								{userInfo.value.tokenExp ? userInfo.value.tokenExp / 24 / 60 / 60 / 1000 : "--"}
							</el-form-item>
						</el-form>
					</div>
				</div>
			);
		};
	}
});

interface PasswordForm {
	oldPwd: string;
	newPwd: string;
	confirmPwd: string;
}
const PwdInfo = defineComponent({
	setup() {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const demoId = ref(DEMOID);
		const loading = ref(false);
		const { userInfo, setToken } = PublicStore();
		const router = useRouter();
		const pwdForm = reactive<PasswordForm>({ oldPwd: "", newPwd: "", confirmPwd: "" });
		const validatePass = (rule: any, value: any, callback: any) => {
			if (value === "") {
				callback(new Error(proxy?.$t("porfile.error.pwd")));
			} else if (value !== pwdForm.newPwd) {
				callback(new Error(proxy?.$t("porfile.error.inconsistent")));
			} else {
				callback();
			}
		};
		const formRules = reactive({
			oldPwd: [{ required: true, message: proxy?.$t("porfile.formrules.oldpwd"), trigger: "change" }],
			newPwd: [{ required: true, message: proxy?.$t("porfile.formrules.newpwd"), trigger: "change" }],
			confirmPwd: [{ required: true, trigger: "blur", validator: validatePass }]
		});
		type FormInstance = InstanceType<typeof ElForm>;
		const formRef = ref<FormInstance>();
		const changePwd = () => {
			formRef.value?.validate(async valid => {
				if (!valid) return;
				// let { success, message } = await checkUserPassWord({ username: userInfo.username, password: pwdForm.oldPwd });
				// if (!success) {
				// 	ElMessage.error({ message: message });
				// 	return;
				// }
				let { code, message } = await modifyUserPassWord({
					username: userInfo.username,
					password: pwdForm.oldPwd,
					newPassword: pwdForm.newPwd
				});
				let ok = showTips(code, "修改密码", message);
				if (ok) {
					pwdForm.oldPwd = "";
					pwdForm.newPwd = "";
					pwdForm.confirmPwd = "";
					formRef.value?.resetFields();
					ElMessageBox.confirm("您是否确认退出登录?", "温馨提示", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning"
					}).then(async () => {
						const authStore = AuthStore();
						authStore.setDeptList([]);
						// 1.调用退出登录接口
						await logoutApi();
						// 2.清除 Token
						setToken("");
						// 3.重定向到登陆页
						router.replace(LOGIN_URL);
					});
				}
			});
		};
		return () => {
			return (
				<div class="password-setting">
					<div class="group-title font-bold pb-3 mb-7 border-b-2">{proxy?.$t("porfile.card_title.modify")}</div>
					<el-form model={pwdForm} ref={formRef} rules={formRules} label-width="80px" size="large">
						<el-form-item prop="oldPwd" label={proxy?.$t("porfile.form_label.oldpwd")}>
							<el-input v-model={pwdForm.oldPwd} placeholder={proxy?.$t("porfile.placeholder.oldpwd")} type="password">
								{{
									prefix: () => {
										return <span class="el-input__icon iconfont iconbx-lock" />;
									}
								}}
							</el-input>
						</el-form-item>
						<el-form-item prop="newPwd" label={proxy?.$t("porfile.form_label.newpwd")}>
							<el-input v-model={pwdForm.newPwd} placeholder={proxy?.$t("porfile.placeholder.newpwd")} type="password">
								{{
									prefix: () => {
										return <span class="el-input__icon iconfont iconbx-lock" />;
									}
								}}
							</el-input>
						</el-form-item>
						<el-form-item prop="confirmPwd" label={proxy?.$t("porfile.form_label.confirmpwd")}>
							<el-input v-model={pwdForm.confirmPwd} placeholder={proxy?.$t("porfile.placeholder.confirmpwd")} type="password">
								{{
									prefix: () => {
										return <span class="el-input__icon iconfont iconbx-lock" />;
									}
								}}
							</el-input>
						</el-form-item>
						<el-form-item>
							<div class="flex justify-end w-full pt-4">
								<el-button disabled={demoId.value == userInfo.userId} onClick={changePwd} type="primary" loading={loading.value}>
									{proxy?.$t("porfile.btn.confirm")}
								</el-button>
							</div>
						</el-form-item>
					</el-form>
				</div>
			);
		};
	}
});
const LayoutInfo = defineComponent({
	setup() {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const globalStore = GlobalStore();
		const themeConfig = computed(() => globalStore.themeConfig);

		// 切换布局方式
		const changeLayout = (val: string) => {
			globalStore.setThemeConfig({ ...themeConfig.value, layout: val });
		};
		return () => {
			return (
				<div class="layout-settting">
					<div class="group-title font-bold pb-3 mb-4 border-b-2">{proxy?.$t("porfile.card_title.personalize")}</div>
					<div class="layout-box">
						<div class="grid md:grid-cols-3 gap-4 text-center w-full">
							<div>
								<div
									class={`layout-item layout-classic ${themeConfig.value.layout == "three" ? "is-active" : ""} m-auto`}
									onClick={() => changeLayout("three")}
								>
									<div class="layout-dark"></div>
									<div class="layout-container">
										<div class="layout-light"></div>
										<div class="layout-content"></div>
									</div>
									<span v-show={themeConfig.value.layout == "three"} class="iconfont iconcirclecheckfull1" />
								</div>
								<div class="text-sm text-gray-700">{proxy?.$t("porfile.layout.three")}</div>
							</div>
							<div>
								<div
									class={`layout-item layout-transverse ${themeConfig.value.layout == "transverse" ? "is-active" : ""} m-auto`}
									onClick={() => {
										changeLayout("transverse");
									}}
								>
									<div class="layout-dark"></div>
									<div class="layout-content"></div>
									<span v-show={themeConfig.value.layout == "transverse"} class="iconfont iconcirclecheckfull1" />
								</div>
								<div class="text-sm text-gray-700">{proxy?.$t("porfile.layout.transverse")}</div>
							</div>
							<div>
								<div
									class={`layout-item layout-columns ${themeConfig.value.layout == "columns" ? "is-active" : ""} m-auto`}
									onClick={() => changeLayout("columns")}
								>
									<div class="layout-dark"></div>
									<div class="layout-light"></div>
									<div class="layout-content"></div>
									<span v-show={themeConfig.value.layout == "columns"} class="iconfont iconcirclecheckfull1" />
								</div>
								<div class="text-sm text-gray-700">{proxy?.$t("porfile.layout.columns")}</div>
							</div>
						</div>
					</div>
				</div>
			);
		};
	}
});
